<template>
  <div class="recovery-stories">
    <!-- 头部操作区 -->
    <div class="header-section">
      <div class="search-filter">
        <el-input
          v-model="searchText"
          placeholder="搜索故事关键词..."
          clearable
          class="search-input"
          :prefix-icon="Search"
          @keyup.enter="searchStories"
        >
          <template #append>
            <el-button type="danger" @click="searchStories">搜索</el-button>
          </template>
        </el-input>

        <div class="filter-group">
          <el-select v-model="filterYear" placeholder="年份" clearable>
            <el-option
              v-for="year in yearOptions"
              :key="year"
              :label="`${year}年`"
              :value="year"
            />
          </el-select>

          <el-select v-model="filterRegion" placeholder="地区" clearable>
            <el-option
              v-for="region in regionOptions"
              :key="region"
              :label="region"
              :value="region"
            />
          </el-select>
        </div>
      </div>

      <el-button
        type="danger"
        class="new-story-btn"
        @click="showSubmissionDialog"
      >
        <el-icon><EditPen /></el-icon>分享我的故事
      </el-button>
    </div>

    <!-- 数据统计 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="8" v-for="stat in stats" :key="stat.title">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <div class="stat-icon" :style="{ background: stat.color }">
                <el-icon><component :is="stat.icon" /></el-icon>
              </div>
              <div class="stat-text">
                <div class="value">{{ stat.value }}</div>
                <div class="title">{{ stat.title }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 故事列表 -->
    <el-row :gutter="20" class="story-list">
      <el-col
        v-for="story in paginatedStories"
        :key="story.id"
        :xs="24"
        :sm="12"
        :md="8"
        :lg="6"
      >
        <el-card class="story-card" shadow="hover">
          <!-- 封面图 -->
          <div class="cover-container" @click="openStory(story)">
            <el-image
              :src="story.cover"
              class="cover-image"
              fit="cover"
            >
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
              <div class="cover-overlay">
                <span class="recovery-date">{{ formatDate(story.recoveryDate) }}</span>
              </div>
            </el-image>
          </div>

          <!-- 故事信息 -->
          <div class="story-info">
            <h3 class="title" @click="openStory(story)">{{ story.title }}</h3>
            <div class="meta">
              <span class="age">
                <el-icon><User /></el-icon>{{ story.age }}岁
              </span>
              <el-divider direction="vertical" />
              <span class="location">
                <el-icon><Location /></el-icon>{{ story.region }}
              </span>
            </div>
          </div>

          <!-- 互动操作 -->
          <div class="action-bar">
            <el-button
              type="danger"
              :icon="Check"
              :class="{ 'liked': story.isLiked }"
              @click="toggleLike(story)"
            >
              {{ story.likes }}
            </el-button>

            <el-dropdown trigger="click">
              <el-button type="danger" :icon="Share" />
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="shareStory(story, 'wechat')">
                    <el-icon><ChatDotRound /></el-icon>微信分享
                  </el-dropdown-item>
                  <el-dropdown-item @click="shareStory(story, 'weibo')">
                    <el-icon><Postcard /></el-icon>微博分享
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <el-button
              type="danger"
              :icon="ChatDotRound"
              @click="openCommentPanel(story)"
            >
              {{ story.comments.length }}
            </el-button>


          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[8, 12, 16]"
        layout="total, sizes, prev, pager, next"
        :total="filteredStories.length"
        background
      />
    </div>

    <!-- 故事详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      :title="currentStory?.title"
      width="90%"
      top="5vh"
      class="story-detail-dialog"
    >
      <div v-if="currentStory" class="detail-content">
        <!-- 时间线 -->
        <el-timeline class="timeline-section">
          <el-timeline-item
            v-for="event in currentStory.timeline"
            :key="event.date"
            :timestamp="formatDate(event.date)"
            placement="top"
            :type="getEventType(event.type)"
            :color="getEventColor(event.type)"
            :icon="getEventIcon(event.type)"
          >
            <el-card shadow="never">
              <h4 class="event-title">{{ event.title }}</h4>
              <p class="event-content">{{ event.content }}</p>
              <el-carousel
                v-if="event.images?.length"
                :interval="5000"
                indicator-position="outside"
                height="300px"
              >
                <el-carousel-item v-for="(img, index) in event.images" :key="index">
                  <el-image
                    :src="img"
                    fit="scale-down"
                    class="event-image"
                  />
                </el-carousel-item>
              </el-carousel>
            </el-card>
          </el-timeline-item>
        </el-timeline>

        <!-- 评论区 -->
        <div class="comment-section">
          <h3 class="comment-title">祝福留言（{{ currentStory.comments.length }}）</h3>

          <div class="comment-list">
            <div
              v-for="comment in currentStory.comments"
              :key="comment.id"
              class="comment-item"
            >
              <el-avatar :src="comment.avatar" size="small" />
              <div class="comment-content">
                <div class="comment-header">
                  <span class="username">{{ comment.username }}</span>
                  <span class="time">{{ formatTime(comment.time) }}</span>
                </div>
                <p class="text">{{ comment.content }}</p>
              </div>
            </div>
          </div>

          <div class="comment-editor">
            <el-input
              v-model="newComment"
              type="textarea"
              :rows="3"
              placeholder="写下你的祝福..."
              resize="none"
              maxlength="200"
              show-word-limit
            />
            <div class="editor-actions">
              <el-button type="danger" @click="submitComment">发表评论</el-button>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 故事提交表单弹窗 -->
    <el-dialog
      v-model="submissionVisible"
      title="分享你的故事"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="submissionForm"
        :model="newStory"
        :rules="submissionRules"
        label-position="top"
      >
        <el-form-item label="故事标题" prop="title">
          <el-input v-model="newStory.title" />
        </el-form-item>

        <el-form-item label="封面图片" prop="cover">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleCoverUpload"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="详细经过" prop="content">
          <el-input
            v-model="newStory.content"
            type="textarea"
            :rows="5"
            resize="none"
          />
        </el-form-item>

        <el-form-item label="时间线事件" prop="timeline">
          <div class="timeline-editor">
            <div
              v-for="(event, index) in newStory.timeline"
              :key="index"
              class="timeline-event"
            >
              <el-input v-model="event.date" placeholder="日期" />
              <el-input v-model="event.title" placeholder="事件标题" />
              <el-input v-model="event.content" placeholder="事件描述" />
            </div>
            <el-button type="danger" @click="addTimelineEvent">添加事件</el-button>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="submissionVisible = false">取消</el-button>
        <el-button type="danger" @click="submitStory">提交故事</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, UploadFile } from 'element-plus'
import {
  Search,
  EditPen,
  Check,
  ChatDotRound,
  Share,
  User,
  Location,
  Picture,
  Postcard,
  Plus,
  SuccessFilled,
  AlarmClock,
  Calendar
} from '@element-plus/icons-vue'

// 类型定义
interface TimelineEvent {
  date: string
  title: string
  content: string
  type: 'missing' | 'search' | 'found'
  images?: string[]
}

interface Comment {
  id: number
  username: string
  avatar: string
  content: string
  time: string
}

interface Story {
  id: number
  title: string
  cover: string
  age: number
  region: string
  recoveryDate: string
  missingDays: number
  likes: number
  isLiked: boolean
  comments: Comment[]
  timeline: TimelineEvent[]
}

interface StoryForm {
  title: string
  cover: string
  content: string
  timeline: Array<{
    date: string
    title: string
    content: string
  }>
}

// 响应式状态
const stories = ref<Story[]>([])
const currentStory = ref<Story | null>(null)
const searchText = ref('')
const filterYear = ref<number | null>(null)
const filterRegion = ref('')
const currentPage = ref(1)
const pageSize = ref(8)
const detailVisible = ref(false)
const submissionVisible = ref(false)
const newComment = ref('')
const submissionForm = ref<FormInstance>()
const newStory = ref<StoryForm>({
  title: '',
  cover: '',
  content: '',
  timeline: []
})

// 表单验证规则
const submissionRules = {
  title: [
    { required: true, message: '请输入故事标题', trigger: 'blur' },
    { min: 5, max: 50, message: '长度在5到50个字符', trigger: 'blur' }
  ],
  cover: [
    { required: true, message: '请上传封面图片', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请填写详细经过', trigger: 'blur' }
  ]
}

// 计算属性
const yearOptions = computed(() => {
  const years = [...new Set(stories.value.map(s =>
    new Date(s.recoveryDate).getFullYear()
  ))]
  return years.sort((a, b) => b - a)
})

const regionOptions = computed(() => {
  return [...new Set(stories.value.map(s => s.region))]
})

const filteredStories = computed(() => {
  return stories.value.filter(story => {
    const textMatch = searchText.value ?
      story.title.toLowerCase().includes(searchText.value.toLowerCase()) ||
      story.region.toLowerCase().includes(searchText.value.toLowerCase()) :
      true

    const yearMatch = filterYear.value ?
      new Date(story.recoveryDate).getFullYear() === filterYear.value :
      true

    const regionMatch = filterRegion.value ?
      story.region === filterRegion.value :
      true

    return textMatch && yearMatch && regionMatch
  })
})

const paginatedStories = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return filteredStories.value.slice(start, start + pageSize.value)
})

const stats = computed(() => [
  {
    title: '成功案例',
    value: stories.value.length,
    color: '#ff6b6b',
    icon: SuccessFilled
  },
  {
    title: '平均找回时间',
    value: stories.value.length > 0 ?
      `${Math.round(
        stories.value.reduce((sum, s) => sum + s.missingDays, 0) / stories.value.length
      )}天` : 'N/A',
    color: '#ff9f6b',
    icon: AlarmClock
  },
  {
    title: '今年找回',
    value: stories.value.filter(s =>
      new Date(s.recoveryDate).getFullYear() === new Date().getFullYear()
    ).length,
    color: '#ff6b9f',
    icon: Calendar
  }
])

// 方法
const formatDate = (dateStr: string) => {
  return new Date(dateStr).toLocaleDateString()
}

const formatTime = (timeStr: string) => {
  return new Date(timeStr).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
}

const openStory = (story: Story) => {
  currentStory.value = story
  detailVisible.value = true
}

const toggleLike = (story: Story) => {
  story.isLiked = !story.isLiked
  story.likes += story.isLiked ? 1 : -1
}

const submitComment = async () => {
  if (!newComment.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }

  if (currentStory.value) {
    currentStory.value.comments.push({
      id: Date.now(),
      username: '当前用户',
      avatar: 'https://dummyimage.com/40x40/ff6b6b/fff',
      content: newComment.value,
      time: new Date().toISOString()
    })
    newComment.value = ''
    ElMessage.success('评论已发布')
  }
}

const handleCoverUpload = (file: UploadFile) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    newStory.value.cover = e.target?.result as string
  }
  if (file.raw) {
    reader.readAsDataURL(file.raw)
  }
}

const addTimelineEvent = () => {
  newStory.value.timeline.push({
    date: '',
    title: '',
    content: ''
  })
}

const submitStory = async () => {
  if (!submissionForm.value) return
  const valid = await submissionForm.value.validate()
  if (!valid) return

  const newId = Date.now()
  stories.value.unshift({
    id: newId,
    ...newStory.value,
    age: 0, // 需要添加实际字段
    region: '', // 需要添加实际字段
    recoveryDate: new Date().toISOString(),
    missingDays: 0, // 需要计算实际值
    likes: 0,
    isLiked: false,
    comments: [],
    timeline: newStory.value.timeline.map(event => ({
      ...event,
      type: 'search', // 需要实际类型判断
      images: []
    }))
  })

  submissionVisible.value = false
  ElMessage.success('故事提交成功')
}

const getEventColor = (type: string) => {
  const colors = {
    missing: '#ff6b6b',
    search: '#ff9f6b',
    found: '#6bff6b'
  } as const
  return colors[type as keyof typeof colors] || '#6b6bff'
}

const getEventIcon = (type: string) => {
  const icons = {
    missing: 'warning-filled',
    search: 'search',
    found: 'success-filled'
  } as const
  return icons[type as keyof typeof icons] || 'question-filled'
}

const getEventType = (type: string) => {
  const types = {
    missing: '失踪',
    search: '搜索',
    found: '找回'
  } as const
  return types[type as keyof typeof types] || '未知类型'
}

const searchStories = () => {
  // 实现搜索故事的逻辑
  console.log('搜索故事:', searchText.value);
}

const showSubmissionDialog = () => {
  submissionVisible.value = true;
}

const openCommentPanel = (story: Story) => {
  currentStory.value = story;
  detailVisible.value = true;
}

const shareStory = (story: Story, platform: string) => {
  // 实现分享故事的逻辑
  console.log(`分享故事到 ${platform}:`, story);
}

// 添加示例数据
stories.value = [
  {
    id: 1,
    title: '失踪的孩子',
    cover: 'https://picsum.photos/260/240?random=1',
    age: 10,
    region: '北京',
    recoveryDate: '2023-01-15',
    missingDays: 30,
    likes: 5,
    isLiked: false,
    comments: [],
    timeline: [
      { date: '2023-01-01', title: '失踪', content: '在公园失踪', type: 'missing' },
      { date: '2023-01-10', title: '搜索', content: '警方开始搜索', type: 'search' },
    ],
  },
  {
    id: 2,
    title: '失踪的老人',
    cover: 'https://picsum.photos/260/240?random=2',
    age: 75,
    region: '上海',
    recoveryDate: '2023-02-20',
    missingDays: 10,
    likes: 3,
    isLiked: false,
    comments: [],
    timeline: [
      { date: '2023-02-15', title: '失踪', content: '在家附近失踪', type: 'missing' },
      { date: '2023-02-18', title: '搜索', content: '家属报案', type: 'search' },
    ],
  },
  {
    id: 3,
    title: '失踪的青年',
    cover: 'https://picsum.photos/260/240?random=3',
    age: 22,
    region: '广州',
    recoveryDate: '2023-03-05',
    missingDays: 5,
    likes: 8,
    isLiked: false,
    comments: [],
    timeline: [
      { date: '2023-03-01', title: '失踪', content: '在学校失踪', type: 'missing' },
      { date: '2023-03-03', title: '搜索', content: '同学们开始寻找', type: 'search' },
    ],
  },
];

</script>


<style lang="scss" scoped>
@use "sass:color";

$primary-color: #409EFF;
$secondary-color: #ff9f6b;
$danger-color: #ff6b6b;

.recovery-stories {
  padding: 12px;
  width: 100%;
  margin: 0 auto;

  .header-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 5px;
    padding: 24px;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);

    .search-filter {
      flex: 1;
      display: flex;
      gap: 16px;
      align-items: center;

      .search-input {
        flex: 1;
        :deep(.el-input-group__append) {
          background-color: $primary-color;
          border-color: $primary-color;
          .el-button {
            color: white;
            transition: all 0.3s ease;
            &:hover {
              background-color: color.scale($primary-color, $lightness: -8%);
            }
          }
        }
      }

      .filter-group {
        display: flex;
        gap: 12px;
        .el-select {
          width: 140px;
          :deep(.el-input__inner) {
            &::placeholder {
              color: #999;
            }
          }
        }
      }
    }

    .new-story-btn {
      padding: 12px 24px;
      font-size: 16px;
      border-radius: 8px;
      transition: all 0.3s ease;
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba($primary-color, 0.2);
      }
    }
  }

  .stats-section {
    margin-bottom: 12px;
    .stat-card {
      border: none;
      border-radius: 12px;
      transition: transform 0.3s ease;
      &:hover {
        transform: translateY(-5px);
      }

      .stat-content {
        display: flex;
        align-items: center;

        .stat-icon {
          width: 48px;
          height: 48px;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 16px;
          font-size: 24px;
          color: #fff;
          transition: all 0.3s ease;
        }

        .stat-text {
          .value {
            color: $primary-color;
            font-size: 28px;
            font-weight: 700;
            line-height: 1.3;
          }
          .title {
            font-size: 15px;
            margin-top: 6px;
          }
        }
      }
    }
  }

  .story-list {
    margin-bottom: 12px;

    .story-card {
      border: none;
      border-radius: 12px;
      margin-bottom: 10px;
      transition: all 0s;

      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 20px rgba($primary-color, 0.12);
      }

      .cover-container {
        width: 100%;
        height: 240px;
        overflow: hidden;
        position: relative;
        .cover-overlay {
          .recovery-date {
            font-size: 14px;
          }
        }
        .image-error .el-icon {
          font-size: 40px;
        }
      }

      .story-info {
        padding: 5px 24px;
        display: flex;
        flex-direction: column;
        text-align: center;
        .title {
          font-size: 19px;
          margin-bottom: 8px;
        }
        .meta {
          gap: 15px;
          font-size: 14px;
          margin-bottom: 10px;
          .el-icon {
            font-size: 16px;
          }
        }
      }

      .action-bar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 24px;
        .el-button {
          width: 60px;
        }
      }
    }
  }

  .pagination-section {
    margin-top: 32px;
    display: flex;
    justify-content: center;
    :deep(.el-pagination) {
      .btn-prev, .btn-next, .el-pager li {
        margin: 0 5px;
      }
    }
  }

  .story-detail-dialog {
    & :deep(.el-dialog) {
        .el-dialog__title {
          font-size: 20px;
        }


      .timeline-section {
        padding: 32px;
        .el-timeline-item {
          padding-bottom: 40px;
          &__node {
            width: 20px;
            height: 20px;
          }
          .el-card {
            &__header {
              padding: 20px;
            }
            .event-content {
              padding: 20px;
              font-size: 15px;
            }
          }
        }
      }

      .comment-section {
        padding: 32px;
        .comment-title {
          font-size: 20px;
          margin-bottom: 24px;
        }
        .comment-item {
          padding: 20px;
          .text {
            font-size: 15px;
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .recovery-stories {
    padding: 16px;

    .header-section {
      padding: 16px;
      .new-story-btn {
        margin-top: 16px;
      }
    }

    .story-card {
      .action-bar .el-button {
        flex: 1 1 48%;
      }
    }

    .story-detail-dialog :deep(.el-carousel) {
      height: 200px !important;
    }
  }
}

:root {
  --el-color-primary: #{$primary-color};
  --el-color-danger: #{$danger-color};
}

.el-button--danger {
  &:hover, &:focus {
    background-color: color.scale($primary-color, $lightness: -8%);
  }
}


::-webkit-scrollbar {
  width: 8px;
  &-thumb {
    background: rgba($primary-color, 0.4);
  }
}
:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #ff4444;
}
</style>
